package com.hljx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hljx.vo.HospitalAreasVO;
import com.hljx.config.exception.DataException;
import com.hljx.dto.HospitalAreaDTO;
import com.hljx.dto.HospitalAreaPageDTO;
import com.hljx.entity.SysAccountingUnit;
import com.hljx.entity.SysHospitalArea;
import com.hljx.mapper.sys.SysHospitalAreaMapper;
import com.hljx.service.SysAccountingUnitService;
import com.hljx.service.SysHospitalAreaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 院区管理 服务实现类
 * </p>
 *
 * @author gx
 * @since 2023-09-18
 */
@Service
public class SysHospitalAreaServiceImpl extends ServiceImpl<SysHospitalAreaMapper, SysHospitalArea> implements SysHospitalAreaService {

    @Autowired
    SysAccountingUnitService accountingUnitService;

    @Override
    public List<SysHospitalArea> listHospitalArea() {
        return this.list();
    }

    @Override
    public Boolean saveOrUpdateHospitalArea(HospitalAreaDTO dto) {
        long count = count(Wrappers.lambdaQuery(SysHospitalArea.class).eq(SysHospitalArea::getCode, dto.getCode())
                     .ne(dto.getId() != null, SysHospitalArea::getId, dto.getId()));
        if(count>0){
            throw new DataException("编码重复",201);
        }
        SysHospitalArea sysHospitalArea = new SysHospitalArea();
        BeanUtil.copyProperties(dto,sysHospitalArea);
        return saveOrUpdate(sysHospitalArea);
    }

    @Override
    public Boolean deleteHospitalArea(Long id) {
        SysHospitalArea sysHospitalArea = getOne(new LambdaQueryWrapper<SysHospitalArea>().eq(SysHospitalArea::getId, id));
        long count = accountingUnitService.count(new LambdaQueryWrapper<SysAccountingUnit>().eq(SysAccountingUnit::getHospitalId, sysHospitalArea.getId()));
        if(count>0){
            throw new DataException("该院区被核算单元引用，无法删除",201);
        }
        return removeById(id);
    }

    @Override
    public IPage<HospitalAreasVO> listHospitalAreaByPage(HospitalAreaPageDTO dto) {
        Page<HospitalAreasVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        return baseMapper.listHospitalAreaByPage(page, dto);
    }
}
